package com.cloud.photo.album.persist.dao.impl;

import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;

import com.cloud.photo.album.persist.dao.Dao;

public class DaoBase<T> implements Dao<T> {

	protected SqlSession session;
	
	private DefaultSqlSessionFactory sqlSessionFactory;
	
	private String prefix;
	private Class<T> clazz;
	
	public void openSession() {
		session = sqlSessionFactory.openSession(true);
	}
	
	@Override
	public T[] select(Map<String, String> map) {
		if(session == null) {
			openSession();
		}
		@SuppressWarnings("unchecked")
		List<T> resultList = (List<T>)session.selectList(new StringBuilder(prefix).append(".select").toString(), map);
		if(resultList == null || resultList.size() == 0) {
			return null;
		} 
		@SuppressWarnings("unchecked")
		T[] resultArray = (T[]) Array.newInstance(clazz, resultList.size());
		for(int i = 0, length = resultList.size(); i < length; i++) {
			resultArray[i] = resultList.get(i);
		}
		return resultArray;
	}

	@Override
	public int update(T t) {
		if(session == null) {
			openSession();
		}
		int result = session.update((new StringBuilder(prefix).append(".update").toString()), t);
		return result;
	}

	@Override
	public int add(T t) {
		if(session == null) {
			openSession();
		}
		int result = session.insert((new StringBuilder(prefix).append(".insert").toString()), t);
		return result;
	}

	@Override
	public int deleteById(int id) {
		if(session == null) {
			openSession();
		}
		return 0;
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public Class<T> getClazz() {
		return clazz;
	}

	public void setClazz(Class<T> clazz) {
		this.clazz = clazz;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T selectObject(T t) {
		if(session == null) {
			openSession();
		}
		return (T) session.selectOne((new StringBuilder(prefix).append(".selectObject").toString()), t);
	}

	
	
	public DefaultSqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

	public void setSqlSessionFactory(DefaultSqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	@Override
	public T[] selectObjectList(T t) {
		if(session == null) {
			openSession();
		}
		@SuppressWarnings("unchecked")
		List<T> resultList = (List<T>)session.selectList(new StringBuilder(prefix).append(".selectObjectList").toString(), t);
		if(resultList == null || resultList.size() == 0) {
			return null;
		} 
		@SuppressWarnings("unchecked")
		T[] resultArray = (T[]) Array.newInstance(clazz, resultList.size());
		for(int i = 0, length = resultList.size(); i < length; i++) {
			resultArray[i] = resultList.get(i);
		}
		return resultArray;
	}


}
